package org.brisling.medical.queryService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletResponse;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ChartDomain;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.common.util.DateUtil;
import org.brisling.common.util.LongUtil;
import org.brisling.common.util.StringUtil;
import org.brisling.medical.domain.MedicalRecipel;
import org.brisling.sysman.domain.Users;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>Title: QueryRecipelService</p>
 * <p>Description: 医疗服务质询记录service</p>
 * <p>Company: tongking</p>
 * @author peter fan
 * @since 1.0
 * @version 1.0
 * @date 2016年7月20日 下午10:13:08
 */
@RestController
@RequestMapping("/medicalRecipel/query")
public class QueryRecipelService extends AbstractBaseQueryService<MedicalRecipel>{
	
	
	
	@Autowired
	private	ShiroSecurityService shiroSecurityService;
	@Autowired
	private QueryDictionaryService dicService;
	public QueryRecipelService(){
		this.moduleName = ConstSysParam.MODULE_RECIPEL;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = ConstSysParam.VIEW_PREFIX +this.moduleName;
		this.clazz = MedicalRecipel.class;
		
		typeMap = this.getTypeMap(clazz);
		
		orderMap.put("inquiry_date", "desc");
		orderMap.put("bizno", "desc");
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	@RequestMapping("/allPage.action")
	public ModelAndView getAllPage(){
		return new ModelAndView("/medical/medical_recipel/all");
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	@RequestMapping("/edit1Page.action")
	public ModelAndView getEditNumPage(){
		
			return new ModelAndView("/medical/medical_recipel/editDlg1");
	}
	
	@RequestMapping("/edit2Page.action")
	public ModelAndView getEdit2Page(){
		
			return new ModelAndView("/medical/medical_recipel/editDlg2");
	}
	
	@RequestMapping("/edit3Page.action")
	public ModelAndView getEdit3Page(){
		
			return new ModelAndView("/medical/medical_recipel/editDlg3");
	}
	
	
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<MedicalRecipel> getListDomain(
			@RequestBody(required=false) String body){		
		
		return super.getListDomainByConditionAndOrder(body, typeMap, orderMap,true);
	}
	
	@RequestMapping("/getBetweenListDomain.action")
	public ListDomain<MedicalRecipel> getBetweenListDomain(
			@RequestBody(required=false) String body){		
		String sql = "select * from medical_recipel r where 1=1"
				+ " <#if inquiry_item_code??> and r.inquiry_item_code = ${inquiry_item_code}</#if> "
				+ " <#if doct_depart_code??> and r.doct_depart_code = ${doct_depart_code}</#if> "
				+ " <#if doct_id??> and r.doct_id = ${doct_id}</#if> "
				+ " <#if inquiry_item_subcode??> and r.inquiry_item_subcode = ${inquiry_item_subcode}</#if> "
				+ " <#if date_end??> and r.inhzospitalat <=  TO_DATE ('${date_end} 23:59:59','yyyy-mm-dd hh24:mi:ss')</#if> "
				
				+ " <#if date_start??> and r.inhzospitalat >=  TO_DATE ('${date_start} 00:00:00','yyyy-mm-dd hh24:mi:ss') "
				+ " and (r.outhospitalat >=  TO_DATE ('${date_start} 00:00:00','yyyy-mm-dd hh24:mi:ss') or outhospitalat is null )</#if>";
		
		String _sql = dicService.getSqlByBizcode("medical_biz_list");
		
		sql = _sql ==null?sql:_sql;
		
		Map<String,Object> map =getBodyParam(body);	
		
		Map<String,Object> paramMap = (Map<String, Object>) map.get("condition");
		sql = StringUtil.formatSql(sql,paramMap );
		
		Integer[] pages = LongUtil.getPageParam(map);
		
		return super.getPagedListDomain(pages[0], pages[1], sql);
// 		return super.getListDomainByConditionAndOrder(body, typeMap, orderMap,true);
	}
	
	@RequestMapping("/getOperateTaskListDomain.action")
	public ListDomain<MedicalRecipel> getUserCanoperateTask(@RequestBody(required=false) String body){
		String sql = dicService.getSqlByBizcode("flow_can_operate");
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> conditionMap = this.getBodyParam(body);
		return super.getUserTaskCanOperateListDomain(userid,sql, conditionMap);
	}
	
	
	public ListDomain<MedicalRecipel> getUserCanoperateTaskList(String userid){
		String sql = dicService.getSqlByBizcode("flow_can_operate");
		
		Map<String, Object> conditionMap = new HashMap<String, Object>();
		return super.getUserTaskCanOperateListDomain(userid,sql, conditionMap);
	}
	
	@RequestMapping("/getSignedTaskListDomain.action")
	public ListDomain<MedicalRecipel> getUserSignedTask(@RequestBody(required=false) String body){
		String sql = dicService.getSqlByBizcode("flow_signed");
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> conditionMap = this.getBodyParam(body);
		return super.getUserSignedListDomain(userid,sql, conditionMap,null);
	}
	
	@RequestMapping("/getUnsignedTaskListDomain.action")
	public ListDomain<MedicalRecipel> getUserUnsignedTask(@RequestBody(required=false) String body){
		String sql = dicService.getSqlByBizcode("flow_can_signed");
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> conditionMap = this.getBodyParam(body);
		return super.getUserUnsignedListDomain(userid,sql, conditionMap,null);
	}
	
	
	@RequestMapping("/getFinishedTaskListDomain.action")
	public ListDomain<MedicalRecipel> getUserFinishedTask(@RequestBody(required=false) String body){
		String sql = dicService.getSqlByBizcode("flow_finished");
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> conditionMap = this.getBodyParam(body);
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all"))
			conditionMap = this.addDeptConditionToMap(userid,conditionMap, "doct_depart_code");
			
		return super.getUserFinishedListDomain(sql, conditionMap,null);
	}
	
	
	@RequestMapping("/getAllTaskListDomain.action")
	public ListDomain<MedicalRecipel> getAllTask(@RequestBody(required=false) String body){
		String sql = dicService.getSqlByBizcode("medical_flow_all_task");
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> conditionMap = this.getBodyParam(body);
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all"))
			conditionMap = this.addDeptConditionToMap(userid,conditionMap, "doct_depart_code");
			
		return super.getAllListDomain(sql, conditionMap,null);
	}
	@SuppressWarnings("unchecked")
	@RequestMapping("/getUserManagedTaskDomain.action")
	public ListDomain<MedicalRecipel> getUserManagedTask(@RequestBody(required=false) String body){
		String sql = dicService.getSqlByBizcode("flow_managed_manageuser");
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> conditionMap = this.getBodyParam(body);
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			Users usr = SysConfig.getUsr(userid);
			if(this.isManageJob(userid)){
				conditionMap = this.addDeptConditionToMap(userid,conditionMap, "doct_depart_code");
			}else{
				Map<String,String> paramMap = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
				if(paramMap==null){
					paramMap = new HashMap<String,String>();
				}
				paramMap.put("user_id_", usr.getIdentify());
				conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
				sql = dicService.getSqlByBizcode("flow_managed_normaluser"); 
			}
		}
		return super.getUserManagedListDomain(sql, conditionMap,null);
	}
	
	@RequestMapping("/exportExcel.action")
	public void exportExcel(@RequestBody(required=false) String body,HttpServletResponse response){
		ListDomain<MedicalRecipel> domains= this.getTaskListDomain(body);
		String configStr = dicService.getSqlByBizcode("medical_inquiry_export");
		super.exportExcel(domains, response, "医疗服务质询", "", configStr);
		
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/getTaskListDomain.action")
	public ListDomain<MedicalRecipel> getTaskListDomain(@RequestBody(required=false) String body){
		
		
		ListDomain<MedicalRecipel> domains = new ListDomain<MedicalRecipel>();
		Map<String,Object> conditionMap = this.getBodyParam(body);
		if((conditionMap!=null) && (conditionMap.containsKey("condition"))){
			Map<String,String> cMap = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
			String _state = null;
			if((cMap!=null) && (cMap.containsKey("flow_state"))){
				_state = cMap.get("flow_state");				
			}else{
				_state = ConstSysParam.FLOW_CANOPERATE;
			}			
			switch(_state){
			case ConstSysParam.FLOW_CANOPERATE:
				domains = getUserCanoperateTask(body);
				break;
//			case ConstSysParam.FLOW_SIGNED:
//				domains = getUserSignedTask(body);
//				break;
//			case ConstSysParam.FLOW_UNSIGED:
//				domains = getUserUnsignedTask(body);
//				break;
			case ConstSysParam.FLOW_MANAGED:
				domains = getUserManagedTask(body);
				break;
			case ConstSysParam.FLOW_all:
				domains = getAllTask(body);
				break;
			case ConstSysParam.FLOW_FINISHED:
				domains = getUserFinishedTask(body);
				break;
			default:
				domains = getUserCanoperateTask(body);
				break;
			}
		}
		return domains;
	}
	
	/**
	 * 获取任务数量
	 * @return
	 */
	@RequestMapping("/getTaskCnt.action")
	public List<ChartDomain> getTaskCnt(@RequestBody(required=false) String body){
		
		List<ChartDomain> domains = new ArrayList<ChartDomain>();
		String issue = "medical";
		Long canOpera = null;
		Long managed = null;
		Long finished = null;
		ListDomain<MedicalRecipel> inquirys = this.getUserCanoperateTask(null);
		
		canOpera = inquirys.getTotal();
		ChartDomain operate = new ChartDomain("待处理",issue,canOpera);
		domains.add(operate);
		
		inquirys = this.getUserManagedTask(null);
		managed = inquirys.getTotal();
		ChartDomain manage = new ChartDomain("处理中",issue,managed);
		domains.add(manage);
		
		inquirys = this.getUserFinishedTask(body);
		finished = inquirys.getTotal();
		ChartDomain finish = new ChartDomain("已处理",issue,finished);
		domains.add(finish);
		
		return domains;
		
	}
	@RequestMapping("/getList.action")
	public List<MedicalRecipel> getList(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="deptid",required=false) Integer deptid,
			@RequestParam(value="sort",required=false) String sort){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		if(deptid!=null){
			String whereCorse=String.format(sb.append("\"deptid\" = %1$d").toString(),deptid);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		return super.getPagedList(page,rows,sql);
	}
	
	/**
	 * 查询所有记录
	 * @return
	 */
	@RequestMapping("/getListAll.action")
	public List<MedicalRecipel> getListAll(){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		
		sql = String.format(this.T_SQL, this.tableName);
		
		
		return super.getAllList(sql);
	}
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public MedicalRecipel getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public MedicalRecipel getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByField.action")
	public MedicalRecipel getOneByField(@RequestParam(value="field",required=false) String field,
			@RequestParam(value="fieldVal",required=false) String fieldVal){	
		return super.getOneByIdentify(field,fieldVal);
	}
	/**
	 * 获取图表所需全部数据
	 * @param body
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/getStaticInfoAll.action")
	public LinkedHashMap getStaticInfoAll(@RequestBody(required=false) String body){
		LinkedHashMap map = new LinkedHashMap(); 
		map.put("fee", getStaticGroupInfo(5));
		map.put("drug", getStaticGroupInfo(6));
		map.put("check", getStaticGroupInfo(7));
		map.put("other", getStaticGroupInfo(8));
		return map;
	}
	
	@SuppressWarnings("rawtypes")
	private List<LinkedHashMap> getStaticGroupInfo(Integer code){
		String sql = "select d.name as \"name\",v.issue as \"issue\",v.y as \"y\" from sysman_dictionary d,(select r.issue,count(r.issue) as y from v_medical_recipel r where R.INQUIRY_ITEM_CODE= %1$d group by issue) v "
				+ "where v.issue = D.BIZCODE " ;
		sql = String.format(sql, code);
		return super.getMappedList(sql);
	}
	
	@SuppressWarnings("unchecked")
	public Long getBizCount(String body){
		
		Map<String,Object> map = this.getBodyParam(body);
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		
		return this.getBizCount(paramMap);
	}
	
	public Long getBizCount(Map<String,String> paramMap){
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			String deptids = getUserDeptids(userid);
			paramMap.put("doct_depart_code_in", deptids);
		}
		String sql = dicService.getSqlByBizcode("medical_inpatient_query");
		return super.getBizCount(paramMap, sql, null, null);
	}
	
	/**
	 * 返回流程记录流程实例的执行记录
	 * @param body	包含procInstId在内的参数信息
	 * @return
	 */
	
	@RequestMapping("/flowHistoricsListDomain.action")
	public ListDomain<Object> getHistoricByProcInstId(@RequestBody(required=false) String body){
		
		String sql = dicService.getSqlByBizcode("flow_historics");				
		return super.getHistoricByProcInstId(body, sql);
	}
	
	public String generateBizno(){
		return super.generateBizno();
	}
	
	
	/**
	 * 医疗服务处方类质询服務异常数据
	 * @return
	 */	
	
	public List<MedicalRecipel> getRecipelAbnormal(){		
		
		String sql =dicService.getSqlByBizcode("medical_reciple");
		
		//sql = new String("select * from medical_anti_dose");
		sql = String.format(sql, DateUtil.getYestodayMonthDay()[2]);
		
		try {
			return super.getClassedAllList(sql, MedicalRecipel.class);
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 	
		return null;
	}
	
	@RequestMapping("/getAllList.action")
	public List<MedicalRecipel> getAllList(){		
		
		
		String	sql = "select * from medical_recipel where inquiry_item_code = 53";
		
		
		return super.getAllList(sql);
	}
	/**
	 * 根据sql获取domain
	 * @return
	 */
	public List<MedicalRecipel> getAllList(String sql){		
		
		return super.getAllList(sql);
	}
}
